/**
 * 
 */
package project.teg.database;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import project.teg.games.game.gestures.Measurement;
import com.db4o.Db4o;
import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;
import android.content.Context;
import android.util.Log;

public class DBHelper {

	private static ObjectContainer oc = null;
	private Context context;

	public DBHelper(Context ctx) {
		context = ctx;
	}

	private ObjectContainer db() {
		try {
			if (oc == null || oc.ext().isClosed())
				oc = Db4o.openFile(Db4o.newConfiguration(),
						db4oDBFullPath(context));
			return oc;
		} catch (Exception e) {
			Log.e(DBHelper.class.getName(), e.toString());
			return null;
		}
	}

	public String db4oDBFullPath(Context ctx) {
		return ctx.getDir("data", 0) + "/" + "android2.db4o";
	}

	public void close() {
		if (oc != null) {
			oc.close();
			oc = null;
		}
	}

	public void insertMeasurement(Measurement entry) {
		entry.setTimeCreated(new Date());
		entry.id = getNextMeasurementID();
		entry.isSent = false;
		db().store(entry);
		db().commit();
	}
	
	public void saveMeasurement(Measurement entry) {
		db().store(entry);
		db().commit();
	}

	public ObjectSet<Measurement> getAllMeasurements() {
		return db().query(Measurement.class);
	}

	public List<Measurement> getSentMeasurements() {
		List<Measurement> m = new ArrayList<Measurement>();
		ObjectSet<Measurement> rea = getAllMeasurements();
		for(Measurement mm : rea){
			if(mm.isSent)
				m.add(mm);
		}
		return m;
	}

	public List<Measurement> getUnSentMeasurements() {
		List<Measurement> m = new ArrayList<Measurement>();
		ObjectSet<Measurement> rea = getAllMeasurements();
		for(Measurement mm : rea){
			if(!mm.isSent)
				m.add(mm);
		}
		return m;
	}

	public Measurement getMeasurementById(int id) {
		Measurement t = new Measurement();
		t.id = id;
		ObjectSet<Measurement> set = db().queryByExample(t);
		if (set.size() < 1)
			return null;
		else
			return (Measurement) set.get(0);
	}

	public long getNextMeasurementID() {
		ObjectSet<Measurement> set = getAllMeasurements();
		long max = 0;
		for (Measurement m : set) {
			if (max < m.id)
				max = m.id;
		}
		return max + 1;
	}
	
	public void setMeasurementsSent(){
		ObjectSet<Measurement> measurements = getAllMeasurements();
		for(Measurement measurement : measurements){
			measurement.isSent=true;
			saveMeasurement(measurement);
		}
	}

	public void deleteDatabase() {
		close();
		new File(db4oDBFullPath(context)).delete();
	}

	public void backup(String path) {
		db().ext().backup(path);
	}

	public void restore(String path) {
		deleteDatabase();
		new File(path).renameTo(new File(db4oDBFullPath(context)));
		new File(path).delete();
	}
}
